<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { templateApi } from '@/api'
import { showConfirmDialog, showToast } from 'vant'

const router = useRouter()
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const templates = ref([])
const searchValue = ref('')

// 分页参数
const pageParams = ref({
  pageNo: 1,
  pageSize: 10,
  keyword: ''
})

// 加载模板列表
const loadTemplates = async (isRefresh = false) => {
  if (isRefresh) {
    pageParams.value.pageNo = 1
    templates.value = []
    finished.value = false
  }

  loading.value = true

  try {
    const params = {
      ...pageParams.value,
      keyword: searchValue.value
    }

    const result = await templateApi.getTemplateList(params)

    if (isRefresh) {
      templates.value = result.records
    } else {
      templates.value.push(...result.records)
    }

    // 判断是否还有更多数据
    if (result.records.length < pageParams.value.pageSize) {
      finished.value = true
    } else {
      pageParams.value.pageNo++
    }
  } catch (error) {
    showToast('加载失败: ' + error.message)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 搜索
const onSearch = () => {
  loadTemplates(true)
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  loadTemplates(true)
}

// 删除模板
const deleteTemplate = async (template) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除模板"${template.name}"吗？`,
    })

    await templateApi.deleteTemplate(template.id)
    showToast('删除成功')
    loadTemplates(true)
  } catch (error) {
    if (error !== 'cancel') {
      showToast('删除失败: ' + error.message)
    }
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取字段预览（显示前3个字段）
const getFieldsPreview = (fields) => {
  if (!fields) return ''
  const fieldArray = fields.split(',').filter(f => f.trim())
  if (fieldArray.length <= 3) {
    return fieldArray.join(', ')
  }
  return fieldArray.slice(0, 3).join(', ') + '...'
}

onMounted(() => {
  loadTemplates(true)
})
</script>

<template>
  <div class="page-container">
    <van-nav-bar
      title="订阅模板管理"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 搜索栏 -->
    <van-search
      v-model="searchValue"
      placeholder="搜索模板名称"
      @search="onSearch"
      @clear="onSearch"
    />

    <!-- 添加按钮 -->
    <van-cell-group>
      <van-cell
        title="新建模板"
        is-link
        @click="router.push('/templates/create')"
        icon="plus"
      />
    </van-cell-group>

    <!-- 模板列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadTemplates"
      >
        <van-cell-group v-for="template in templates" :key="template.id" class="template-item">
          <van-cell>
            <template #title>
              <div class="template-title">{{ template.name }}</div>
            </template>
            <template #label>
              <div class="template-info">
                <div>范围类型: {{ template.scopeType === 'SYSTEM' ? '系统订阅' : '各关订阅' }}</div>
                <div>订阅模式: {{ template.subscribeMode === 'RAW' ? '原始数据' : '汇总数据' }}</div>
                <div>数据格式: {{ template.dataFormat }}</div>
                <div>数据源: {{ template.dataSource }}</div>
                <div v-if="template.groupFields">汇总字段: {{ template.groupFields }}</div>
                <div v-if="template.selectedFields">选择字段: {{ getFieldsPreview(template.selectedFields) }}</div>
                <div>更新时间: {{ formatDateTime(template.updatedTime) }}</div>
              </div>
            </template>
          </van-cell>

          <van-cell-group>
            <van-cell
              title="编辑"
              is-link
              @click="router.push(`/templates/${template.id}/edit`)"
              icon="edit"
            />
            <van-cell
              title="删除"
              is-link
              @click="deleteTemplate(template)"
              icon="delete"
              title-style="color: #ee0a24;"
            />
          </van-cell-group>
        </van-cell-group>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<style scoped>
.template-item {
  margin-bottom: 12px;
}

.template-title {
  font-weight: 500;
  font-size: 16px;
}

.template-info {
  margin-top: 4px;
  font-size: 12px;
  color: #969799;
}

.template-info div {
  margin-bottom: 2px;
}
</style>
